package com.example.mysqldemo.service;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.example.mysqldemo.entity.TicketEntity;
import com.example.mysqldemo.mapper.TicketMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import javax.sql.DataSource;

@Service
public class MyService {

    private final TransactionTemplate transactionTemplate;
    private final TicketMapper ticketMapper;

    @Autowired
    public MyService(TransactionTemplate transactionTemplate, TicketMapper ticketMapper) {
        this.transactionTemplate = transactionTemplate;
        this.ticketMapper = ticketMapper;
    }

    // 使用 TransactionTemplate 执行事务,无结果返回
    public void executeWithTransaction() {
        transactionTemplate.setIsolationLevel(TransactionTemplate.ISOLATION_READ_COMMITTED);
        transactionTemplate.executeWithoutResult(status -> {
            try {
                // 执行数据库操作
                ticketMapper.update(null,new LambdaUpdateWrapper<TicketEntity>().set(TicketEntity::getNum,5)
                        .eq(TicketEntity::getId,1));
                // 如果此处抛出异常，事务将回滚
            } catch (DataAccessException e) {
                status.setRollbackOnly(); // 手动标记回滚
                throw e; // 抛出异常以触发回滚
            }
        });
    }

    // 使用 TransactionTemplate 执行事务，并返回结果
    public Object executeWithResult() {
        return transactionTemplate.execute(status -> {
            // 执行查询或更新，并返回结果
            int count =  ticketMapper.update(null,new LambdaUpdateWrapper<TicketEntity>().set(TicketEntity::getNum,5)
                    .eq(TicketEntity::getId,1));
            return count;
        });
    }
}